package MetaApp;

import java.util.*;

public class Three {

    public static void main(String[] args) {
        int[] array = new int[]{6, 2, 3, 1};
        System.out.print(getThree(array));
    }

    public static int answer(int[] x) {
        int one = getOne(x);
        int[] two = getTwo(one);
        int three = getThree(two);
        return three;
    }

    private static int getThree(int[] array) {
        Set<Integer> set = new TreeSet<>();
        for (int i = 0; i < array.length; i++) {
            set.add(Math.abs(array[i]));
        }
        int[] newArray = new int[set.size()];
        int index = 0;
        for (Integer i : set) {
            newArray[index++] = i;
        }
        int result = 2;
        for (int i = 1; i < newArray.length; i++) {
            if (newArray[i] - newArray[i - 1] >= 2) {
                result += 2;
            } else {
                result += 1;
            }
        }
        return result;
    }

    private static int[] getTwo(int n) {
        n = n < 0 ? -n : n;
        if (n == 0) return new int[0];
        if (n > 8) return new int[]{1, 2, 3, 4, 5, 6, 7, 8};
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = i + 1;
        }
        return result;
    }

    private static int getOne(int[] array) {
        int len = array.length;
        if (len < 2) return 0;
        // 当后面有涨值大于2的话就可以买
        // 当后面有落差大于2的话就可以卖（如果有涨，别卖，下一个基点）
        int result = 0;
        int leftIndex = 0;
        int rightIndex = 0;
        while (true) {
            int[] indexs = getPoint(array, leftIndex);
            if (indexs.length == 0) break;
            leftIndex = indexs[0];
            rightIndex = indexs[1];
            rightIndex = getRightPoint(array, rightIndex);
            result += array[rightIndex] - array[leftIndex] - 2;
            leftIndex = leftIndex + 1;

        }
        return result;
    }

    private static int getRightPoint(int[] array, int start) {
        // 当后面有落差大于2的话就可以卖（如果有涨，别卖，下一个基点）
        for (int i = start; i < array.length; i++) {
            if (array[i] >= array[start]) {
                start = i;
                continue;
            }
            if (array[i] - array[start] > 2) {
                break;
            }
        }
        return start;
    }

    private static int[] getPoint(int[] array, int start) {
        // 只要有涨过2的就可以买
        for (int i = start + 1; i < array.length; i++) {
            if (array[i] - array[start] > 2) {
                return new int[]{start, i};
            }
        }
        return new int[0];
    }
}
